import request from '../utils/request';

export function fetch(params) {
  let url = `api/bugs/`;

  if (!params) {
    return request(url);
  }
  if (params) {
    let paramsArray = [];
    //拼接参数
    Object.keys(params).forEach(key => paramsArray.push(key + '=' + params[key]));
    if (url.search(/\?/) === -1) {
      url += '?' + paramsArray.join('&');
    } else {
      url += '&' + paramsArray.join('&');
    }
  }
  return request(url);
}

export function patch(id, values) {
  return request(`api/bugs/${id}/`, {
    method: 'PUT',
    headers: {
      'Content-Type': 'application/json',
      'X-CSRFToken': getCookie('csrftoken'),
    },
    body: JSON.stringify(values),
  });
}

export function create(values) {
  return request('api/bugs/', {
    method: 'POST',
    headers: {
      'Content-type': 'application/json',
      'X-CSRFToken': getCookie('csrftoken'),
    },
    body: JSON.stringify(values),
  });
}

function getCookie(name) {
  let arr, reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)');
  if (arr = document.cookie.match(reg))
    return decodeURI(arr[2]);
  else
    return null;
}
